package com.flow.framework.lock.service.system.health.impl;

import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.common.util.random.RandomUtil;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import com.flow.framework.lock.enumeration.FrameworkHealthCheckLockKeyEnum;
import com.flow.framework.lock.helper.LockHelper;
import com.flow.framework.lock.properties.FrameworkLockConfigProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;

/**
 * Redisson健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/3/13
 */
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
@RequiredArgsConstructor
public class RedissonHealthCheckServiceImpl implements IHealthCheckService {

    private final FrameworkLockConfigProperties frameworkLockConfigProperties;

    /**
     * @inheritDoc
     */
    @Override
    public List<ServiceHealthVo> check() {
        Boolean enable = frameworkLockConfigProperties.getEnable();
        if (!VerifyUtil.isTrue(enable)) {
            return Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.SERVICE_DISTRIBUTION_LOCK_CODE));
        }
        try {
            String uuid = RandomUtil.randomNoShortLineUuid();
            return LockHelper.resultLockExecute(null, FrameworkHealthCheckLockKeyEnum.FRAMEWORK_HEALTH_CHECK_LOCK_KEY,
                    Collections.singletonList(uuid),
                    1000, () ->
                            Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.SERVICE_DISTRIBUTION_LOCK_CODE))
            );
        } catch (Exception e) {
            log.error("check redisson error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_DISTRIBUTION_LOCK_CODE,
                            e.getMessage(), null)
            );
        }
    }
}
